import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 32309
 * Date: 2025-07-05
 * Time: 16:47
 */
public class demo_DriverManager {
    public static void main(String[] args) throws SQLException {

        Connection connection = null;

        Statement statement = null;

        ResultSet resultSet = null;
        try {
            // 1. 加载数据库厂商的驱动
            // 通过完全限定名加载指定的类加载到JVM，将相关驱动类注册到DriverManager中
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8" + "&allowPublicKeyRetrieval=true&useSSL=false", "root", "580231");

            // 3. 创建statement对象
            statement = connection.createStatement();

            // 4. 定义SQL并且执行
            // 接受用户的输入
            System.out.println("请输入学生姓名：");
            Scanner scanner = new Scanner(System.in);
            String name = scanner.nextLine();
            String sql = "select student_id,sn,name,mail,class_id from student where name = '"+ name + "' ";

            // 5. 获取查询结果集
            resultSet = statement.executeQuery(sql);// 专门执行select查询的方法

            // 6. 对结果集遍历，获取所有结果
            // 有下一行返回true
            while (resultSet.next()) {
                Long id = resultSet.getLong(1);
                String stu_sn = resultSet.getString(2);
                String stu_name = resultSet.getString(3);
                String stu_mail = resultSet.getString(4);
                long classId = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生编号 = {0}, 学号 = {1}, 姓名 = {2}, 邮箱 = {3}, 班级编号 = {4}",id,stu_sn,stu_name,stu_mail,classId));
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭连接，释放资源
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        }

    }
}
